<!-- 模板复制弹窗-->
<template>
  <a-modal
    width="40%"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    title-align="center"
    unmount-on-close
  >
    <template #title> 模板复制 </template>
    <div>
      <a-form :model="formData" ref="refForm" :rules="rules" auto-label-width>
        <a-form-item label="新模板名称" field="name" show-colon>
          <a-input v-model="formData.name"></a-input>
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button @click="handleOk" type="primary">确认</a-button>
      <a-button @click="handleEdit" type="primary">确认并编辑</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { cloneDeep } from 'lodash';
import { CheckHumanChangeSetting } from '@/apis/management/human/baseSetting/humanSetting';
import { validateRules } from '@/utils/common';
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    validateFun?: any; // 校验函数
    data?: any; // 传入的数据
  }>(),
  {
    visible: false
  }
);

const emits = defineEmits(['update:visible', 'copyEmit', 'copyEditEmit']);
let refForm = ref();

// 模板名称查重校验
const validateName = async (val: string, cb: any) => {
  try {
    if (props.validateFun) {
      const res = await props?.validateFun(val);
      if (res.code) cb(`${res.msg}`);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = {
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ]
};

let formData = ref({
  name: ''
});

watch(
  () => props.visible,
  (newVal: boolean) => {
    if (props?.data) {
      formData.value = cloneDeep(props.data);
      formData.value.name = '';
    } else {
      formData.value = {
        name: ''
      };
    }
  }
);

const handleOk = async () => {
  if (await refForm.value.validate()) {
    return;
  }
  emits('copyEmit', formData.value);
  emits('update:visible', false);
};

const handleEdit = async () => {
  if (await refForm.value.validate()) {
    return;
  }
  emits('copyEditEmit', formData.value);
  emits('update:visible', false);
};

const handleCancel = () => {
  emits('copyEmit', null);
  emits('update:visible', false);
};
</script>

<style scoped lang="less">
.icon {
  cursor: pointer;
  font-size: 20px;
}
</style>
